package com.blackhorse.service.impl;


import com.blackhorse.dao.ProductDao;
import com.blackhorse.domain.Product;
import com.blackhorse.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    @Override
    public Product findByPid(Integer pid) {
        return productDao.findById(pid).orElse(null);
    }

    @Transactional
    @Override
    public void reduceInventory(Integer pid, Integer number) {
        Optional<Product> productOpt = productDao.findById(pid);
        //省略校验...
        Product product = productOpt.get();
        //扣减库存
        product.setStock(product.getStock() - number);

        //模拟异常（如果没有分布式事务管理，异常会导致下单成功，但没有扣减库存）
//        int i = 1 / 0;

        //保存数据库
        productDao.save(product);
    }
}
